package com.jianyun.jyzs.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.fragment.HaveDoFragment;
import com.jianyun.jyzs.fragment.ShareTaskFragment;
import com.jianyun.jyzs.fragment.WaitDoFragment;
import com.jianyun.jyzs.presenter.FlowExaminePresenter;
import com.jianyun.jyzs.utils.Const;
import com.jianyun.jyzs.utils.LocalSp;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.RceLog;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.utils.WorkFlowActHelper;
import com.jianyun.jyzs.view.iview.IFlowExamineView;
import com.jianyun.jyzs.widget.SearchPopWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jianyun.jyzs.activity.FlowExamineHtmlActivity.shenPiRefreshYes;
import static com.jianyun.jyzs.activity.FlowExamineHtmlActivity.shenpiRefresh;

/**
 * 流程审批界面
 * Created by yangshijun on 2018/5/29.
 */

public class FlowExamineActivity extends MvpActivity<IFlowExamineView,
        FlowExaminePresenter> implements IFlowExamineView {
    @BindView(R.id.imgbtn_custom_nav_back)
    ImageButton imgbtnCustomNavBack;
    @BindView(R.id.imgbtn_custom_nav_finish)
    ImageButton imgbtnCustomNavFinish;
    @BindView(R.id.tv_custom_nav_title)
    TextView tvCustomNavTitle;
    @BindView(R.id.tv_custom_nav_sub_title)
    TextView tvCustomNavSubTitle;
    @BindView(R.id.ll_custom_nav_title)
    LinearLayout llCustomNavTitle;
    @BindView(R.id.tv_custom_nav_option)
    TextView tvCustomNavOption;
    @BindView(R.id.imgbtn_custom_nav_option)
    ImageButton imgbtnCustomNavOption;
    @BindView(R.id.imgbtn_custom_nav)
    ImageButton imgbtnCustomNav;
    @BindView(R.id.rl_actionbar)
    RelativeLayout rlActionbar;
    @BindView(R.id.tab_1)
    TextView tab1;
    @BindView(R.id.tab_2)
    TextView tab2;
    @BindView(R.id.tab_3)
    TextView tab3;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.slide_1)
    ImageView slide1;
    @BindView(R.id.slide_2)
    ImageView slide2;
    @BindView(R.id.slide_3)
    ImageView slide3;
    @BindView(R.id.vPager)
    ViewPager vPager;


    private int selectedColor;
    private int unSelectedColor;
    private ImageView imageView;
    private int bmpW;
    private int offset = 0;// 动画图片偏移量
    public int currIndex = 0;// 当前页卡编号

    /**
     * 页卡总数
     **/
    private static final int pageSize = 3;
    public List<Fragment> fragments;// Tab页面列表
    public WaitDoFragment waitDoFragment;// Tab页面列表单独缓存第1个页签
    public HaveDoFragment havaDoFragment;// Tab页面列表单独缓存第2个页签
    public ShareTaskFragment shareTaskFragment;// Tab页面列表单独缓存第3个页签

    public String createUserId;
    public SearchPopWindow searchPopWindow;
    public TextView textViewTemp;//popwindow上
    private int flowSwtich;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_workflow);
        ButterKnife.bind(this);
        flowSwtich = LoginCache.getInstance().getFlowSwtich();
        initData();
        initView();
    }

    private void initData() {
        LocalSp.getInstance().clearTopCount(1);
        tvCustomNavTitle.setText(R.string.top_workFlow_app);
        imgbtnCustomNavOption.setImageResource(R.drawable.detail_search_default);
        if (0 == flowSwtich || -1 == flowSwtich) {
            imgbtnCustomNav.setImageResource(R.drawable.rce_title_option_hover);
            imgbtnCustomNav.setVisibility(View.INVISIBLE);
        }

    }

    private void initView() {
        selectedColor = getResources().getColor(R.color.blue);
        unSelectedColor = getResources().getColor(R.color.content2);
        InitImageView();
        InitTextView();
        InitViewPager();
        String jumpUrl = getIntent().getStringExtra("jumpUrl");
        if (!TextUtils.isEmpty(jumpUrl)) {
            waitDoFragment.setJumpUrl(jumpUrl);
        }
        String appName = getIntent().getStringExtra("appName");
        if (!TextUtils.isEmpty(appName)) {
            if (appName.equals("1")) {
                vPager.setCurrentItem(0);
                tab1.setTextColor(selectedColor);
                tab2.setTextColor(unSelectedColor);
                tab3.setTextColor(unSelectedColor);

                tab1.setText("我的待办");
                tab2.setText("我的已办");
                tab3.setText("共享任务");
            } else if (appName.equals("2")) {
                vPager.setCurrentItem(1);
                tab1.setTextColor(unSelectedColor);
                tab2.setTextColor(selectedColor);
                tab3.setTextColor(unSelectedColor);

                tab1.setText("我的待办");
                tab2.setText("我的已办");
                tab3.setText("共享任务");
            } else if (appName.equals("3")) {
                vPager.setCurrentItem(2);
                tab1.setTextColor(unSelectedColor);
                tab2.setTextColor(unSelectedColor);
                tab3.setTextColor(selectedColor);
                tab1.setText("我的待办");
                tab2.setText("我的已办");
                tab3.setText("共享任务");
            }
        }
    }

    /**
     * 初始化动画，这个就是页卡滑动时，下面的横线也滑动的效果，在这里需要计算一些数据
     */

    private void InitImageView() {
        imageView = (ImageView) findViewById(R.id.slide_1);
        bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.tab_selected_bg).getWidth();// 获取图片宽度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 获取分辨率宽度
        offset = (screenW / pageSize - bmpW) / 2;// 计算偏移量--(屏幕宽度/页卡总数-图片实际宽度)/2
        int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量											// = 偏移量
        Animation animation = new TranslateAnimation(one * currIndex, one * 0, 0, 0);// 显然这个比较简洁，只有一行代码。
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        imageView.startAnimation(animation);
    }

    @OnClick({R.id.imgbtn_custom_nav_back, R.id.imgbtn_custom_nav_option, R.id.imgbtn_custom_nav})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgbtn_custom_nav_back:
                finish();
                break;
            case R.id.imgbtn_custom_nav_option:
                switch (currIndex) {
                    case 0://
                        searchPopWindow = new SearchPopWindow(this, R.layout.popupwindow_workflow_search, waitDoFragment.data);
                        searchPopWindow.showPopupWindow(imgbtnCustomNavOption);
                        break;
                    case 1://
                        searchPopWindow = new SearchPopWindow(this, R.layout.popupwindow_workflow_search, havaDoFragment.data);
                        searchPopWindow.showPopupWindow(imgbtnCustomNavOption);
                        break;
                    case 2://
                        searchPopWindow = new SearchPopWindow(this, R.layout.popupwindow_workflow_search, shareTaskFragment.data);
                        searchPopWindow.showPopupWindow(imgbtnCustomNavOption);
                        break;
                    default:
                        break;
                }
                break;

            case R.id.imgbtn_custom_nav:
                Intent intent = new Intent(this, FlowSwtichActivity.class);

                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == WorkFlowActHelper.GETUSER && resultCode == RESULT_OK) {
            ArrayList<User> users = (ArrayList<User>) data.getSerializableExtra(Const.SELECTED_CONTACTS);
            // ArrayList<User> users = data.getParcelableArrayListExtra(Const.SELECTED_CONTACTS);
            RceLog.d("lml", "list.toString()=" + users.toString());
            if (textViewTemp != null) {
                try {
                    User user = users.get(1);
                    createUserId = user.getServerUserId();
                    textViewTemp.setText(user.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }

        if ( resultCode == shenPiRefreshYes) {
            //需要刷新界面
            Log.i("test", "刷新列表界面");
            //webView.loadUrl(mPrevUrl);
            if(waitDoFragment!=null){
                waitDoFragment.reFreshView();

            }

        }
    }

    /**
     * 初始化头标
     */
    private void InitTextView() {
        tab1 = (TextView) findViewById(R.id.tab_1);
        tab2 = (TextView) findViewById(R.id.tab_2);
        tab3 = (TextView) findViewById(R.id.tab_3);

        tab1.setTextColor(selectedColor);
        tab2.setTextColor(unSelectedColor);
        tab3.setTextColor(unSelectedColor);

        tab1.setText("我的待办");
        tab2.setText("我的已办");
        tab3.setText("共享任务");

        tab1.setOnClickListener(new MyOnClickListener(0));
        tab2.setOnClickListener(new MyOnClickListener(1));
        tab3.setOnClickListener(new MyOnClickListener(2));
    }

    /**
     * 初始化Viewpager页
     */
    private void InitViewPager() {
        fragments = new ArrayList<Fragment>();
        waitDoFragment = new WaitDoFragment();// Tab页面列表单独缓存第1个页签
        havaDoFragment = new HaveDoFragment();// Tab页面列表单独缓存第2个页签
        shareTaskFragment = new ShareTaskFragment();// Tab页面列表单独缓存第3个页签
        fragments.add(waitDoFragment);
        fragments.add(havaDoFragment);
        fragments.add(shareTaskFragment);

        vPager.setOffscreenPageLimit(2);
        vPager.setAdapter(new myPagerAdapter(getSupportFragmentManager(), fragments));
        vPager.setCurrentItem(0);
        vPager.setOnPageChangeListener(new MyOnPageChangeListener());
    }

    /**
     * 为选项卡绑定监听器
     */
    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量
        int two = one * 2;// 页卡1 -> 页卡3 偏移量

        public void onPageScrollStateChanged(int index) {
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        public void onPageSelected(int index) {
            Animation animation = new TranslateAnimation(one * currIndex, one * index, 0, 0);// 显然这个比较简洁，只有一行代码。
            currIndex = index;
            animation.setFillAfter(true);// True:图片停在动画结束位置
            animation.setDuration(300);
            imageView.startAnimation(animation);

            switch (index) {
                case 0:
                    tab1.setTextColor(selectedColor);
                    tab2.setTextColor(unSelectedColor);
                    tab3.setTextColor(unSelectedColor);
                    break;
                case 1:
                    tab1.setTextColor(unSelectedColor);
                    tab2.setTextColor(selectedColor);
                    tab3.setTextColor(unSelectedColor);
                    break;
                case 2:
                    tab1.setTextColor(unSelectedColor);
                    tab2.setTextColor(unSelectedColor);
                    tab3.setTextColor(selectedColor);
                    break;
            }
        }
    }

    /**
     * 定义适配器
     */
    class myPagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;

        public myPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList = fragmentList;
        }

        /**
         * 每个页面的title
         */
        @Override
        public CharSequence getPageTitle(int position) {
            return null;
        }

        /**
         * 页面的总个数
         */
        @Override
        public int getCount() {
            return fragmentList == null ? 0 : fragmentList.size();
        }

        /**
         * 得到每个页面
         */
        @Override
        public Fragment getItem(int arg0) {
            return (fragmentList == null || fragmentList.size() == 0) ? null : fragmentList.get(arg0);
        }
    }

    /**
     * 头标点击监听
     */
    private class MyOnClickListener implements View.OnClickListener {
        private int index = 1;

        public MyOnClickListener(int i) {
            index = i;
        }

        public void onClick(View v) {

            switch (index) {
                case 0:
                    tab1.setTextColor(selectedColor);
                    tab2.setTextColor(unSelectedColor);
                    tab3.setTextColor(unSelectedColor);
                    break;
                case 1:
                    tab1.setTextColor(unSelectedColor);
                    tab2.setTextColor(selectedColor);
                    tab3.setTextColor(unSelectedColor);
                    break;
                case 2:
                    tab1.setTextColor(unSelectedColor);
                    tab2.setTextColor(unSelectedColor);
                    tab3.setTextColor(selectedColor);
                    break;
            }
            vPager.setCurrentItem(index);
        }

    }

    /**
     * 点击查询条件搜索后执行此方法
     */
    public void searchData() {
        switch (currIndex) {
            case 0://
                waitDoFragment.searchData();
                break;
            case 1://
                havaDoFragment.searchData();
                break;
            case 2://
                shareTaskFragment.searchData();
                break;
            default:
                break;
        }

    }

    @NonNull
    @Override
    public FlowExaminePresenter createPresenter() {
        return new FlowExaminePresenter();
    }
}
